
package org.jeecg.modules.demo.admin.service.impl;

import org.jeecg.modules.demo.admin.entity.dto.EmailSentDTO;
import org.jeecg.modules.demo.constant.BaseContext;
import org.jeecg.modules.demo.drfAdmin.service.impl.DrfAdminServiceImpl;
import org.jeecg.modules.demo.drfusers.service.impl.DrfUsersServiceImpl;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.Properties;

@Service
public class DynamicMailServiceImpl {

    private final DrfUsersServiceImpl drfUsersServiceImpl;

    private final DrfAdminServiceImpl drfAdminServiceImpl;

    public DynamicMailServiceImpl(DrfUsersServiceImpl drfUsersServiceImpl, DrfAdminServiceImpl drfAdminServiceImpl) {
        this.drfUsersServiceImpl = drfUsersServiceImpl;
        this.drfAdminServiceImpl = drfAdminServiceImpl;
    }

    /**
     * 发送邮件（使用动态 SMTP 配置）
     *
     *   内容
     * @param isSsl      是否使用 SSL（465 端口用 SSL，587 用 STARTTLS）
     */
    public void sendMail(EmailSentDTO emailSentDTO, boolean isSsl) {
        String host = "smtp.163.com";
        int port = 465;
        String username = "your-email@163.com";
        String password = "your-auth-code";
        //TODO: 获取当前登录人员的id,基于id获取用户昵称
        String userId = String.valueOf(BaseContext.getCurrentId());
        String nickname = drfAdminServiceImpl.getByUserId(userId).getName();
        String to = emailSentDTO.getEmail();
        String subject = "【通知】新任务";
        String content = "您有新的论文评审任务，请登录处理。";

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);

        // 设置协议参数
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        if (isSsl) {
            props.put("mail.smtp.ssl.enable", "true");
        } else {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        mailSender.setJavaMailProperties(props);

        // 构建邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(nickname != null ? nickname + " <" + username + ">" : username);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            System.out.println("✅ 邮件已发送至：" + to);
        } catch (Exception e) {
            System.err.println("❌ 发送失败：" + e.getMessage());
        }
    }
}